// src/utils/request.js
import axios from 'axios'
import { ElMessage } from 'element-plus'  // 替换消息组件导入
import {useUserStore} from '../store/user'

const service = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8070',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json'
    }
})

service.interceptors.request.use(
    (config) => {
        const userStore = useUserStore()
        if (userStore.token) {
            config.headers['Authorization'] = `Bearer ${userStore.token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    (response) => {
        return response.data
    },
    (error) => {
        const errorMessage = error.response?.data?.message ||
            error.message ||
            '请求异常，请检查网络'
            
        // 替换为Element Plus消息提示
        ElMessage({
            message: errorMessage,
            duration: 2000,
            type: 'error'
        })

        if (error.response?.status === 401) {
            const userStore = useUserStore()
            userStore.clearUser()
            window.location.href = '/login'
        }
        return Promise.reject(error)
    }
)

export default service